package controller

import (
	"github.com/gin-gonic/gin"
	"kf/models/dao"
	"kf/models/entity"
	"kf/utils/R"
	"net/http"
	"strconv"
)

// 部门
type DeptController struct {
	SysDeptDao *dao.SysDeptDao
}

// 获取部门简略信息
func (deptController *DeptController) DeptOptions(c *gin.Context) {
	options := deptController.SysDeptDao.ListDeptOptions()
	c.JSON(http.StatusOK, R.ReturnSuccess(options))
}

// 获取部门
func (deptController *DeptController) GetDepts(context *gin.Context) {
	var deptQuery entity.DeptQuery
	err := context.ShouldBindQuery(&deptQuery)
	if err != nil {
		context.JSON(http.StatusInternalServerError, "获取部门失败")
		return
	}
	list, err := deptController.SysDeptDao.GetDepts(deptQuery)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(list))
}

// 查询部门
func (deptController *DeptController) GetDeptForm(context *gin.Context) {
	detpIdStr := context.Param("deptId")
	// 尝试将字符串转换为整数
	deptId, err := strconv.ParseUint(detpIdStr, 10, 64)
	if err != nil {
		// 如果转换失败，返回错误响应
		context.JSON(http.StatusInternalServerError, "Invalid ID")
		return
	}
	form, err := deptController.SysDeptDao.GetDeptForm(deptId)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(form))
}

// 删除
func (deptController *DeptController) DeleteDepts(context *gin.Context) {
	idStr := context.Param("ids")
	b, err := deptController.SysDeptDao.DeleteDepts(idStr)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(b))
}

// 修改部门
func (deptController *DeptController) UpdateDept(context *gin.Context) {
	var deptForm entity.DeptForm
	err := context.ShouldBindJSON(&deptForm)
	var id uint64
	param := context.Param("id")
	id, _ = strconv.ParseUint(param, 10, 64)
	if err != nil {
		context.JSON(http.StatusInternalServerError, "修改部门信息失败")
		return
	}
	result, err := deptController.SysDeptDao.UpdateDept(id, deptForm)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(result))
}

// 保存部门
func (deptController *DeptController) SaveDept(context *gin.Context) {
	var deptForm entity.DeptForm
	err := context.ShouldBindJSON(&deptForm)
	if err != nil {
		context.JSON(http.StatusInternalServerError, "修改部门信息失败")
		return
	}
	result, err := deptController.SysDeptDao.SaveDept(deptForm)
	if err != nil {
		context.JSON(http.StatusOK, R.ReturnFailMsg(err.Error()))
		return
	}
	context.JSON(http.StatusOK, R.ReturnSuccess(result))
}
